<?php

namespace backend\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Check;

/**
 * CheckSearch represents the model behind the search form about `common\models\Check`.
 */
class CheckSearch extends Check
{
    public $cat;
    public $type;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'type', 'times', 'created_at', 'updated_at', 'check_time', 'cat'], 'integer'],
            ['cat', 'default', 'value' => 1],
            ['cat', 'required'],
            [['bl_img'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Check::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->type = $params['type'];
        $this->cat = $params['cat'];
        $this->load($params);
        
        

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'check_time' => $this->check_time,
        ]);
        
        switch($this->type) {
            case 1:
                $query->andWhere(['times' => 3]);
                break;
            case 2:
                $query->andWhere(['and', ['!=', 'times', -1], ['!=', 'times', 3]]);
                break;
            case 3:
                $query->andWhere(['times' => -1]);
                break;
        }
        
        $query->andWhere(['type' => $this->cat]);
        
        $query->andFilterWhere(['like', 'bl_img', $this->bl_img]);

        return $dataProvider;
    }
}
